package com.miya.demo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.monitor4all.logRecord.annotation.OperationLog;
import cn.monitor4all.logRecord.context.LogRecordContext;
import com.miya.demo.entity.Customer;
import com.miya.demo.model.base.BaseResponse;
import com.miya.demo.model.dto.CustomerAddDTO;
import com.miya.demo.model.dto.CustomerEditDTO;
import com.miya.demo.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @PostMapping("/add")
    @OperationLog(bizType = "'customer'", bizId = "#customer.id", msg = "'新增客户: ' + #addDTO.name", extra = "#addDTO", recordReturnValue = true)
    public BaseResponse<Void> add(@RequestBody @Validated CustomerAddDTO addDTO) {
        Customer customer = BeanUtil.copyProperties(addDTO, Customer.class);
        customerService.save(customer);

        // 手动传递日志上下文: bizId
        LogRecordContext.putVariable("customer", customer);
        return BaseResponse.create();
    }

    @GetMapping("/detail")
    @OperationLog(bizType = "'customer'", bizId = "#id", msg = "'查询客户: ' + #id", extra = "#id", recordReturnValue = true)
    public BaseResponse<Customer> detail(Long id) {
        Customer customer = customerService.getById(id);
        return BaseResponse.create(customer);
    }

    @PostMapping("/edit")
    @OperationLog(bizId = "#editDTO.id", bizType = "'customer'", msg = "#_DIFF(#oldObject, #newObject)", extra = "#editDTO", recordReturnValue = true)
    public BaseResponse<Void> edit(@RequestBody @Validated CustomerEditDTO editDTO) {
        Customer oldCustomer = customerService.getById(editDTO.getId());
        Customer newCustomer = new Customer();
        BeanUtil.copyProperties(editDTO, newCustomer);
        customerService.updateById(newCustomer);

        // 手动传递日志上下文: bizId
        LogRecordContext.putVariable("oldObject", oldCustomer);
        LogRecordContext.putVariable("newObject", newCustomer);
        return BaseResponse.create();
    }

}
